package com.github.vortexdev.yachtclub.repository.mysql;

import com.github.vortexdev.yachtclub.models.Owner;
import com.github.vortexdev.yachtclub.repository.OwnerRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Sergey Parakhin (sergey.parahin@gmail.com)
 */
public class MysqlOwnerRepository implements OwnerRepository {
    private JdbcTemplate jdbcTemplate;

    private static final String SELECT_ALL_SQL_TEMPLATE = "SELECT * FROM owners;";

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public List<Owner> findAll() {
        return jdbcTemplate.query(SELECT_ALL_SQL_TEMPLATE, OWNER_MAPPER);
    }

    private static final RowMapper<Owner> OWNER_MAPPER = new RowMapper<Owner>() {
        public Owner mapRow(ResultSet rs, int rowNum) throws SQLException {
            Owner owner = new Owner();
            owner.setOwnerId(rs.getInt("ownerId"));
            owner.setName(rs.getString("name"));
            owner.setCountry(rs.getString("country"));
            owner.setCity(rs.getString("city"));
            owner.setAge(rs.getInt("age"));
            return owner;
        }
    };
}
